package com.xsoft.sms.cmpp20.comm.handlers;

import com.xsoft.sms.cmpp20.comm.listener.IClientListener;
import com.xsoft.sms.cmpp20.message.ICMPP20Message;
import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;

import java.util.Date;

/**
 * package: {PACKAGE_NAME}
 * User: zhanglm
 * Date: 12-9-18
 * Time: 下午3:05
 * Description:
 */
public class CMPP20MessageHandler extends IdleStateAwareChannelHandler {

	private static Logger logger = Logger.getLogger(CMPP20MessageHandler.class);

	private IClientListener listener;

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		super.channelConnected(ctx, e);    //To change body of overridden methods use File | Settings | File Templates.
		listener.clientConnected();
	}

	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		super.channelClosed(ctx, e);    //To change body of overridden methods use File | Settings | File Templates.
		listener.clientDisconnected();
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		if (e.getMessage() instanceof ICMPP20Message) {
			listener.messageReceived((ICMPP20Message) e.getMessage());
		}
//
//		super.messageReceived(ctx, e);    //To change body of overridden methods use File | Settings | File Templates.
	}

	@Override
	public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
		super.channelIdle(ctx, e);    //To change body of overridden methods use File | Settings | File Templates
		long idleTimeoutInSeconds = new Date().getTime() - e.getLastActivityTimeMillis();
		idleTimeoutInSeconds /= 1000;
		listener.idleTimeout(idleTimeoutInSeconds);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		logger.error(e.getCause());

	}
}
